﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeLinkApi.Models.Request;
using WeLinkWeb.Models;

namespace LRSMES.WebUI.Areas.WeLink.Controllers
{
    public class UserInfoController : Controller
    {
        //
        // GET: /WeLink/UserInfo/
        WeLinkApi.WeLinkApi api = new WeLinkApi.WeLinkApi();

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 根据APPID和AppSecret获取AccessToken
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JsonResult GetAccessTokenByID()
        {
            W_AccessTokenRequest request = new W_AccessTokenRequest()
            {
                client_id = ConfigurationManager.AppSettings["AppId"],
                client_secret = ConfigurationManager.AppSettings["AppSecret"]
            };
            var accessToken = api.GetAccessTokenByID(request).access_token;
            Response.Cookies["accessToken"].Value = accessToken;
            return Json(accessToken);
        }


        /// <summary>
        /// 获取用户详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JsonResult GetUserInfoByToken(W_UserInfoRequest request)
        {
            string accessToken = Request.Cookies["accessToken"].Value;
            var result = api.GetUserInfoByToken(request, accessToken);
            return Json(result);
        }
        /// <summary>
        /// 查询用户父级部门
        /// </summary>
        /// <param name="request">根据用户信息（userId、corpUserId、mobileNumber）获取用户所在部门的所有上级父部门信息。</param>
        /// <returns></returns>
        public JsonResult GetUserAllParentDept(W_UserAllParentRequest request)
        {
            string accessToken = Request.Cookies["accessToken"].Value;
            var result = api.GetUserAllParentDept(request, accessToken);
            return Json(result);
        }

        /// <summary>
        /// 查询部门的人员信息列表(详细信息)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JsonResult GetUserInfoDetailOfDept(W_UserInfoOfDeptRequest request)
        {
            string accessToken = Request.Cookies["accessToken"].Value;
            var result = api.GetUserInfoDetailOfDept(request, accessToken);
            var data = new { total = result.total, rows = result.data };
            return Json(data);

        }

        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JsonResult GetDeptmentInfo(W_DeptmentInfoRequest request)
        {
            string accessToken = Request.Cookies["accessToken"].Value;
            var result = api.GetDeptmentInfo(request, accessToken);
            return Json(result);

        }

        /// <summary>
        /// 获取父部门
        /// </summary>信息
        /// <param name="request"></param>
        /// <returns></returns>
        public JsonResult GetParentDeptInfo(W_ParentDeptRequest request)
        {
            string accessToken = Request.Cookies["accessToken"].Value;
            var result = api.GetParentDeptInfo(request, accessToken);
            return Json(result);

        }
        /// <summary>
        /// 获取子部门信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JsonResult GetChildDeptInfo()
        {
            try
            {
                W_ChildDeptRequest request = new W_ChildDeptRequest()
            {
                deptCode = "0",
                recursiveflag = 0,
                offset = 1,
                limit = 100,
            };
                string accessToken = Request.Cookies["accessToken"].Value;
                var ChildDept = api.GetChildDeptInfo(request, accessToken).departmentInfo;

                W_DeptmentInfoRequest data1 = new W_DeptmentInfoRequest()
                {
                    deptCode = "0"
                };
                var RootDept = api.GetDeptmentInfo(data1, accessToken);

                 DeptmentTrees result = new DeptmentTrees()
                {
                    deptCode = RootDept.deptCode,
                    deptNameCn = RootDept.deptNameCn,
                    deptNameEn = RootDept.deptNameEn,
                    children = ChildDept.ToList()
                };

                 List<DeptmentTrees> resultData = new List<DeptmentTrees>();
                 resultData.Add(result);
                return Json(resultData);
            }
            catch (Exception ex)
            {
                var data = new { success = false, message = ex };
                return Json(data);
            }

        }

        /// <summary>
        /// 获取部门人员组织架构
        /// </summary>
        /// <returns></returns>
        public JsonResult GetUserListAndDeptment()
        {
            try
            {
                HttpCookie cookie = Request.Cookies["accessToken"];
                var accessToken = "";
                if (null == cookie)
                {
                    W_AccessTokenRequest request = new W_AccessTokenRequest()
                    {
                        client_id = ConfigurationManager.AppSettings["AppId"],
                        client_secret = ConfigurationManager.AppSettings["AppSecret"]
                    };
                    accessToken = api.GetAccessTokenByID(request).access_token;
                    Response.Cookies["accessToken"].Value = accessToken;
                }
                else
                {
                    accessToken = Request.Cookies["accessToken"].Value;
                }
                W_ChildDeptRequest req = new W_ChildDeptRequest()
                {
                    deptCode = "0",
                    recursiveflag = 0,
                    offset = 1,
                    limit = 100,
                };
                var itemList = api.GetChildDeptInfo(req, accessToken).departmentInfo;

                List<DeptmentTree> data = new List<DeptmentTree>();


                foreach (var item in itemList)
                {
                    W_UserInfoOfDeptRequest user = new W_UserInfoOfDeptRequest()
                    {
                        deptCode = item.deptCode
                    };
                    var result = api.GetUserInfoDetailOfDept(user, accessToken).data;
                    DeptmentTree resultData = new DeptmentTree()
                    {
                        deptCode = "<input type='hidden' value='" + item.deptCode + "'>",
                        deptNameCn = item.deptNameCn,
                        deptNameEn = item.deptNameEn,
                        mobileNumber = "<input type='hidden' value='" + item.deptCode + "'>",
                        children = result.ToList()
                    };
                    data.Add(resultData);
                }

                return Json(data);
            }
            catch (Exception ex)
            {
                var data = new { success = false, message = ex };
                return Json(data);
            }
        }



        /// <summary>
        /// 异步批量同步用户(单个处理，不支持多个添加)
        /// 接受用户信息，异步同步到WeLink通讯录，支持批量更新用户信息，每次请求最多支持10个用户。
        /// </summary>
        public JsonResult UploadUsersByAsyn(string req)
        {
            try
            {
                var personInfo = JsonConvert.DeserializeObject<PersonInfo>(req);
                List<PersonInfo> personInfoArr = new List<PersonInfo>();
                personInfoArr.Add(personInfo);
                W_UploadUsersByAsynRequest request = new W_UploadUsersByAsynRequest()
                {
                    personInfo = personInfoArr
                };
                string accessToken = Request.Cookies["accessToken"].Value;
                var result = api.UploadUsersByAsyn(request, accessToken);
                var data = new { success = result.code != "0" ? false : true, message = result.code != "0" ? "同步人员失败" : "同步人员成功，请等待管理员通过！" };
                return Json(data);
            }
            catch (Exception ex)
            {
                var data = new { success = false, message = ex };
                return Json(data);
            }

        }



        /// <summary>
        /// 异步批量同步部门
        /// 接受部门信息，同步到WeLink通讯录，支持批量更新部门信息，每次请求最多支持10个部门。
        /// </summary>
        public JsonResult UploadDeptsByAsyn(string req)
        {
            try
            {
                var deptInfo = JsonConvert.DeserializeObject<DeptInfo>(req);
                List<DeptInfo> deptInfoArr = new List<DeptInfo>();
                deptInfoArr.Add(deptInfo);

                W_UploadDeptsByAsynRequest request = new W_UploadDeptsByAsynRequest()
                {
                    deptInfo = deptInfoArr
                };
                string accessToken = Request.Cookies["accessToken"].Value;
                var result = api.UploadDeptsByAsyn(request, accessToken);
                var data = new { success = result.code != "0" ? false : true, message = result.code != "0" ? "同步部门失败" : "同步部门成功,请等待管理员通过！" };
                return Json(data);
            }
            catch (Exception ex)
            {
                var data = new { success = false, message = ex };
                return Json(data);
            }

        }


    }
}
